package model.textChat;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;

import model.infocenter.ServerInformations;
import model.textChat.Interface.TChatSocketManage;

public class TChatSocketManager implements TChatSocketManage
{
	private ArrayList<SocketObserver> registers;
	private Socket socket = null;
	private boolean conti = true;
	
	public TChatSocketManager()
	{
		registers = new ArrayList<SocketObserver>();
		updateSocket();
	}
	
	
	public synchronized void register(SocketObserver observer)
	{
		registers.add( observer );
		try 
		{
			observer.update( socket );
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	

	@Override
	public void run() 
	{
	
		while( conti )
		{
			checkSocketStatus();
			
			try
			{
				Thread.sleep( 500 );
			}
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
		}
		
		if ( socket != null )
		{
			try
			{
				socket.close();
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
		
	
	}
	
	
	private synchronized void checkSocketStatus()
	{
		if ( socket == null || socket.isClosed() )
		{
	
			updateSocket();
		}
	}
	
	private void notifyAllObs()
	{
		for (int i = 0; i < registers.size(); i++) 
		{
			try
			{
				registers.get(i).update( socket );
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	private void updateSocket()
	{
		if ( socket != null )
		{
			try 
			{
				socket.close();
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
		
		try 
		{
			String serverIp = ServerInformations.getInstance().getIP();
			socket = new Socket( serverIp, 7575 );
			
	
			
			notifyAllObs();
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}


	@Override
	public void start() 
	{
		Thread tCSMThread = new Thread( this );
		tCSMThread.start();
	}


	@Override
	public synchronized void end() 
	{
		conti = false;
	}
	
	
	
}
